<template>
  <div class="register">
    <el-container>
      <el-main>
        <div>
          <back-to-home-logo></back-to-home-logo>
        </div>
        <div class="card">
          <div class="headFont">
            用户注册
          </div>
          <el-form :model="form" :rules="rules" status-icon ref="form">
            <el-form-item prop="username">
              <el-input class="inputBox" v-model="form.username"
                        placeholder="支持英文、数字和特殊字符，注册后不能更改" prefix-icon="el-icon-user-solid"
                        size="large"></el-input>
            </el-form-item>
            <el-form-item prop="password"  >
              <el-input v-model="form.password" placeholder="8～20位字母、数字或特殊符号"
                        show-password prefix-icon="el-icon-s-goods" size="large"></el-input>
            </el-form-item>
            <el-form-item prop="password2" >
              <el-input v-model="form.password2" placeholder="请重复输入密码"
                        prefix-icon="el-icon-s-goods" size="large" show-password></el-input>
            </el-form-item>
            <el-form-item prop="email"  >
              <el-input v-model="form.email" placeholder="请输入合法的邮箱"
                        prefix-icon="el-icon-s-promotion" size="large"></el-input>
            </el-form-item>
            <el-form-item prop="emailCode">
              <el-space size="large">
                <el-input v-model="form.emailCode" style="width: 300px"
                          placeholder="请输入验证码" maxlength="6" prefix-icon="el-icon-warning"></el-input>
                <el-button :disabled="!canClick"  @click="sendCode" type="success">{{ sendCodeContent }}</el-button>
              </el-space>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="signUp" round @click="register('form')">创建用户</el-button>
            </el-form-item>
            <el-form-item class="register">
              <el-button  type="text" @click="loginClick">已有账号，立即登陆</el-button>
            </el-form-item>

          </el-form>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import BackToHomeLogo from "../../../components/BackToHomeLogo";
import axios from "axios";
import qs from "qs";

export default {
  name: "Login",
  components: {
    BackToHomeLogo,
  },
  data() {
    const usernameCheck = (rule, value, callback) => {
      if(value === ''){
        callback(new Error('请输入用户名，只包含英文和数字'))
      } else {
        const reg = /^[A-Za-z0-9]+$/
        if (!reg.test(value)) {
          callback(new Error('用户名只包含英文字母和数字'))
        } else callback()
      }
    }
    const passwordCheck = (rule, value, callback) => {
      if(value === ''){
        callback(new Error('请输入密码'))
      } else {
        const reg = /^[^\s]*$/
        if (!reg.test(value)) {
          callback(new Error('密码中不能包含空格'))
        } else {
          callback()
        }
      }
    }
    const emailCheck = (rule, value, callback) => {
      if (value === ''){
        callback(new Error('请输入邮箱'))
      } else {
        const reg = /^([a-z0-9]+[_|\_|\.]?)*[a-z0-9]+@([a-z0-9]+[_|\_|\.]?)*[a-z0-9]+\.[a-z]{2,3}$/
        if (!reg.test(value)) {
          callback(new Error('请输入正确的邮箱格式'))
        } else {
          callback()
        }
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.form.password2 !== '') {
          this.$refs.form.validateField('checkPass');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      labelPosition: 'right',
      sendCodeContent: '发送验证码',
      totalTime: 5,
      canClick: true,
      form: {
        username: '',
        password: '',
        password2: '',
        email: '',
        emailCode: ''
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {validator: usernameCheck, trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 8, max: 20, message: '长度为8-20', trigger: 'blur'},
          {validator: passwordCheck, trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        password2: [
          {required: true, message: '请重复输入密码', trigger: 'blur'},
          {validator: validatePass2, trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: emailCheck, trigger: 'blur'}
        ],
        emailCode: [
          {required: true, message: '请输入验证码', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    loginClick() {
      this.$router.push('/login')
    },
    sendCode(){
      if(this.form.email !== '') {
        const data = {
          email: this.form.email
        }
        axios.post('/api/register/sendCode', qs.stringify(data)).then((res) => {
          if (res.data.code === 0) {
            this.$message.success({
              showClose: true,
              message: '发送验证码成功',
              duration: 1500
            })
          } else {
            this.$notify.error(res.data.msg)
          }
        })
      } else {
        this.$message.error('请输入您的邮箱')
        return
      }

      if(!this.canClick) return
      this.canClick = false
      this.sendCodeContent = this.totalTime + 's后重新发送'
      let clock = window.setInterval(() => {
        this.totalTime--
        this.sendCodeContent = this.totalTime + 's后重新发送'
        if(this.totalTime < 0) {
          window.clearInterval(clock)
          this.totalTime = 5
          this.canClick = true
          this.sendCodeContent = '重新发送'
        }
      }, 1000)
    },
    register(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const data = {
            username: this.form.username,
            password1: this.form.password,
            password2: this.form.password2,
            email: this.form.email,
            emailCode: this.form.emailCode
          }
          axios.post('/api/register/commit', qs.stringify(data)).then((res) => {
            console.log(res);
            if(res.data.code === 0){
              this.$message.success({
                showClose: true,
                message: '注册成功！',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  window.open('/login', '_self')
                }
              })
            } else {
              this.$message.error({
                showClose: true,
                message: '注册失败',
                type: 'error',
                duration: 1500
              })
            }
          })
        }
      })
    }
    }
  // }
}
</script>

<style scoped>

.el-main {
  background-color: #409EFF;
  color: #333;
  text-align: center;
  line-height: 160px;
  position: fixed;
  width: 100%;
  height: 100%;



  background-image: url('../img/LoginBackgroundImg.jpg');
  background-repeat: no-repeat;
  background-size: cover;

}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 600px;
}

.register img{
  width: 50px;
  float: left;

}

.card {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  /*position: relative;*/
  box-sizing: border-box;
  width: 500px;
  height: 660px;
  padding: 20px;
  box-shadow: 20px 20px 50px rgba(0, 0, 0, 0.5);
  border-radius: 15px;
  background: rgba(255, 255, 255, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  border-top: 1px solid rgba(255, 255, 255, 0.5);
  border-left: 1px solid rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(5px);
}

.el-input__inner{   /*或者 .s2>>>.el-input__inner  */
  /*background:rgba(0,0,0,0.2);    !*调整inner的背景色，透明*!*/
  border-radius: 50px;    /*输入框圆角值*/
}

.headFont {
  font-size: 32px;
  color: white;
}

.el-button--primary {
  font-size: 22px;
  width: 450px;
  background-color: lightsalmon;
}

.el-button--text {
  color: lightsalmon;
}
.el-button--text:hover{
  color: khaki;
}
.el-button--text:focus{
  color: lightsalmon;
}
.el-button--text:active {
  color: coral;
}

.register {
  font-size: 16px;
  position: relative;
  margin-right: -320px;
}
.code.el-input {
  width: 100px;
}
.el-button--success {
  width: 120px;
  font-size: 14px;
  text-align: center;
}

.signUp {
  background-color: transparent;
  color: white;
}
</style>